import { resolve } from 'path-browserify';

export function transformWatchNum(num) {
  if (num < 10000) {
    return num;
  } else {
    const n = (num / 10000).toFixed(1);
    if (n > 999.9) {
      return '999.9w';
    }
    return n + 'w';
  }
}

// 是否企业微信
export function isWechatCom() {
  const ua = navigator.userAgent.toLowerCase();
  const isWechatCom = ua.indexOf('wxwork') > -1;
  console.log('isWechatCom 是否为企业微信', isWechatCom);
  return isWechatCom;
}
// 是否微信
export function isWechat() {
  const ua = navigator.userAgent.toLowerCase();
  const isWechat = ua.indexOf('micromessenger') > -1 && !isWechatCom();
  console.log('isWechat 是否为微信', isWechat);
  return isWechat;
}

/**
 * 将 queryString 转换成 key-value 形式
 * @param {String} url url地址
 * @returns object
 */
export const parseQueryString = url => {
  return [...new URL(url).searchParams].reduce(
    (cur, [key, value]) => ((cur[key] = value), cur),
    {}
  );
};

/**
 * 动态加载链接
 * @param   {String}  url  要加载的链接
 * @return
 */
export function loadScript(url) {
  return new Promise((resolve, reject) => {
    try {
      var script = document.createElement('script');
      script.src = url;

      // 加载完成后的回调函数
      script.onload = function () {
        resolve('success');
      };
      // 加载失败的回调函数
      script.onerror = function () {
        console.error('Failed to load script: ' + url);
        reject('error');
      };
      // 将 <script> 标签添加到文档中
      document.head.appendChild(script);
    } catch (error) {
      console.error('Failed to load script: ' + error);
      reject(error);
    }
  });
}

/**
 * 存储数据至localStorage
 *
 * @param   {String}  id // 活动id
 * @param   {Object}  query
 *
 */
export function setLocalData(id, query) {
  localStorage.setItem(`local_data_${id}`, JSON.stringify(query));
}
/**
 * 获取localStorage数据
 *
 * @param   {[type]}  id
 *
 * @return  {Object}
 */
export function getLocalData(id) {
  let data = localStorage.getItem(`local_data_${id}`);
  if (data) {
    return JSON.parse(data);
  }
}
